package conf

import (
	"flag"
	"reflect"

	"gopkg.in/ini.v1"
)

type App struct {
	Width, Height int
	Port          int
	LogPath       string
	Public        string
	Name          string
	Addr          string
	LuaPath       string
}

type Config struct {
	App *App
}

func LoadConf(filename string) (cfg *Config, err error) {
	flag.Parse()
	cfgIni, err := ini.Load(filename)
	if err != nil {
		return
	}
	config := reflect.ValueOf(Config{App: &App{}})

	for _, section := range cfgIni.Sections() {
		childConf := config.FieldByName(section.Name())
		if !childConf.IsValid() {
			continue
		}
		for _, key := range section.Keys() {
			if childConf.Kind() == reflect.Ptr {
				childConf = childConf.Elem()
			}
			conf := childConf.FieldByName(key.Name())
			if !conf.IsValid() {
				continue
			}
			switch conf.Kind() {
			case reflect.Int64, reflect.Int32, reflect.Int, reflect.Int16, reflect.Int8:
				conf.SetInt(key.MustInt64(0))
			case reflect.Uint64, reflect.Uint32, reflect.Uint, reflect.Uint16, reflect.Uint8:
				conf.SetUint(key.MustUint64(0))
			case reflect.Bool:
				conf.SetBool(key.MustBool(false))
			default:
				conf.SetString(key.MustString(""))
			}
		}
	}
	c, _ := config.Interface().(Config)
	cfg = &c
	return
}
